package com.mainbo.modular.system.service.impl;

import com.mainbo.modular.system.service.StorageService;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.InputStream;

/**
 * 撰写教案 存储远程调用服务
 * 
 * @author csj
 * @author tmser 2015年3月3日 下午14:38
 * @version $Id: StorageServiceImpl.java, v 1.0 2015年2月6日 下午1:57:24 csj Exp $
 */
@Service
public class LocalStorageServiceImpl implements StorageService {

  private static final Logger logger = LoggerFactory
      .getLogger(LocalStorageServiceImpl.class);
  // 存储服务根目录
  public String basePath = "";

  @Override
  public String upload(InputStream stream, String fileName, String aimUrl) {
    try {
      if (StringUtils.isEmpty(aimUrl)) {
        throw new IllegalStateException("aimUrl cann't be null!");
      }
      File aimFile = new File(basePath, aimUrl);
      File parentFolder = aimFile.getParentFile();
      if (parentFolder != null && !parentFolder.exists()) {
        parentFolder.mkdirs();
      }
      FileUtils.copyInputStreamToFile(stream, aimFile);
      logger.info(">> [save success ] " + aimUrl);
    } catch (Exception e) {
      logger.error("upload file failed ,filename = [{}] ", fileName);
      logger.error("", e);
      throw new RuntimeException("upload file failed", e);
    }
    return aimUrl;
  }

  @Override
  public String download(String aimUrl) {
    File f = new File(basePath, aimUrl);
    return f.getAbsolutePath();
  }

  @Override
  public boolean delete(String aimUrl) {
    boolean flag = false;
    if (StringUtils.isNotEmpty(aimUrl)) {
      File file = new File(basePath, aimUrl);
      if (!file.exists()) {
        logger.info(">> [file doesn't exist] " + aimUrl);
        return true;
      }

      if (file.isFile()) {
        file.delete();
        flag = true;
      }
    }
    return flag;
  }

  @Override
  public String parseDevice(String filepath) {
    return "local";
  }

  /**
   * get base path
   */
  public String getBasePath() {
    return basePath;
  }

  /**
   * set base path
   */
  public void setBasePath(String basePath) {
    this.basePath = basePath;
  }

  @Override
  public String localUrl(String aimUrl) {
    return aimUrl;
  }

}
